package com.company.cloud.sdk.weixin.mini;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.company.cloud.sdk.weixin.common.constant.WxErrorEnum;
import com.company.cloud.sdk.weixin.common.exception.WxException;
import com.company.cloud.sdk.weixin.mini.enums.WxMiniApiType;
import com.company.cloud.sdk.weixin.mini.enums.WxMiniDomain;
import com.company.cloud.sdk.weixin.mini.model.Code2SessionModel;
import com.company.cloud.sdk.weixin.mini.model.Code2SessionResp;
import com.company.cloud.sdk.weixin.mini.model.DecryptDataModel;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Map;

/**
 * 微信小程序API
 */
public class WxMiniApi {

    public static String getReqUrl(WxMiniApiType wxMiniApiType) {
        return getReqUrl(wxMiniApiType, null);
    }

    public static String getReqUrl(WxMiniApiType wxMiniApiType, WxMiniDomain wxMiniDomain) {
        if (wxMiniDomain == null) {
            wxMiniDomain = WxMiniDomain.CHINA;
        }
        return wxMiniDomain.getType().concat(wxMiniApiType.getType());
    }


    /**
     * 登录凭证校验
     */
    public static String code2Session(Map<String, Object> params) {
        try {
            String url = getReqUrl(WxMiniApiType.Code2Session);
            String httpResp = HttpUtil.get(url, params);
            return httpResp;
        } catch (Exception e) {
            throw new WxException(WxErrorEnum.WX_Http_ERROR.getCode(), e.getMessage());
        }

    }

    /**
     * 登录凭证校验
     */
    public static Code2SessionResp code2Session(Code2SessionModel entity) {
        Map<String, Object> params = BeanUtil.beanToMap(entity, false, true);
        String result = WxMiniApi.code2Session(params);
        if (StrUtil.isEmpty(result)) {
            throw new WxException(WxErrorEnum.WX_Http_ERROR);
        }
        Map<String, Object> resultMap = JSON.parseObject(result, Map.class);
        Code2SessionResp data = BeanUtil.fillBeanWithMapIgnoreCase(resultMap, new Code2SessionResp(), false);
        if (data.getErrcode() != null && data.getErrcode() != 0) {
            throw new WxException(data.getErrcode(), data.getErrmsg());
        }
        return data;
    }

//    https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
//    https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
    /***/

    /**
     * 数据解密
     */
    public static JSONObject decryptData(DecryptDataModel entity) {
        if (entity == null) {
            throw new WxException(WxErrorEnum.WX_Para_NULL);
        }
        if (StrUtil.hasEmpty(entity.getEncryptedData(), entity.getIv(), entity.getSessionKey())) {
            throw new WxException(WxErrorEnum.WX_Para_NULL);
        }
        try {
            byte[] encrypData = Base64.decode(entity.getEncryptedData());
            byte[] ivData = Base64.decode(entity.getIv());
            byte[] sessionKeyByte = Base64.decode(entity.getSessionKey());
            AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(sessionKeyByte, "AES");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            //解析解密后的字符串
            String decryptDataResult = new String(cipher.doFinal(encrypData), "UTF-8");
            System.out.println(StrUtil.format("++++解析解密后的字符串={}", decryptDataResult));
            return JSONObject.parseObject(decryptDataResult);
        } catch (Exception e) {
            System.out.println(e);
            throw new WxException(WxErrorEnum.WX_Decrypt_ERROR);
        }
    }

}
